#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>

#include <netdb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string.h>
#include "base64encode.h"

#define PACKET_SIZE_MAX	1428
#define BUFLEN		512

#define SERVER "www.kguard.org"
#define PORT 80

static inline int
connect_http(const char *server, const int port)
{
	struct	sockaddr_in addr;
	struct	hostent *host;
	int s=0, ret = 0, err = 0;

	if((host = gethostbyname(server)) == NULL) {
		err = -1;
		ret = -1;
		goto FX_EXIT;
	}
	addr.sin_family	=	AF_INET;
	addr.sin_port	=	htons(port);

	addr.sin_addr	=	*(struct in_addr*)host->h_addr;

	s = socket(AF_INET, SOCK_STREAM, 0);
	if(s == -1) {
		err = -2;
		ret = -1;
		goto FX_EXIT;
	}

	if(connect(s, (struct sockaddr*)&addr, sizeof(addr)) == -1) {
		err = -3;
		ret = -1;
		goto FX_EXIT;
	}
	printf("    Connect %s(%d) OK....\n", server, port);
FX_EXIT:
	if( ret < 0 ){
		printf("connect_http:error(%d), host:%s, port:%d\n", err,server, port);
		return ret;
	}
	return s;
}

static inline int
request_server(int s, char *server,char *domain,char *login,char *wanip)
{
	int ret = 0, err = 0;
	char *message = NULL;
	char b64user[128]={0};
        
	message = malloc(PACKET_SIZE_MAX);
	if( message == NULL ){
		err = -6;
		ret = -1;
		goto FX_EXIT;
	}
	memset(message, 0, PACKET_SIZE_MAX);
	
	base64encode(login, b64user);
	
	(void)snprintf(message, BUFLEN, 
		"GET /client/update.aspx?host=%s&myip=%s HTTP/1.1\r\n"
		//"GET /client/update.aspx?host=%s HTTP/1.1\r\n"
		"User-Agent: DDNS-Enterprise-Client-v2.0\r\n"
		"Authorization: Basic %s\r\n"
		"Host: %s\r\n"
		"\r\n"
		,domain,wanip,b64user,server);
	if(write(s, message, strlen(message)) == -1) {
		err = -1;
		ret = -1;
		goto FX_EXIT;
	}
	
FX_EXIT:
	if( message != NULL ){
		printf("    request_server2() success\n");
		free(message);
	}
	if( ret < 0 ){
		printf("request_server:error(%d), sock:%d\n", err,s);
	}
	return ret;
}

int main(int argc, char **argv)
{
	int s;
	char *domain=argv[1];
	char *username=argv[2];
	char *password=argv[3];
	char *wanip=argv[4];
	char login[128]={0},wanip_buf[32]={0};
	
	s = connect_http(SERVER,PORT);
	if(s < 0)
		return 0;
	sprintf(login,"%s:%s",username,password);
	if(wanip)
		strcpy(wanip_buf,wanip);
	request_server(s,SERVER,domain,login,wanip_buf);
	
	close(s);
	return 0;	
}
